interface IPosition {
    top: number;
    left: number;
}
class Barrage {
    el: HTMLDivElement;
    speed: number;
    un_speed: number; //反速度
    state: number;  //0:匀速  ,1:减速 ,2:加速
    stateChangeTime: number;
    position: IPosition;

    lastTime: number;  //this.el.style.left  
    constructor(public timer: Timer, public text: string = "未命名") {
        if (timer) {
            timer.add(this.tick.bind(this))
            this.el = document.createElement("div");
            this.el.className = "b-block"
            this.el.textContent = text;
            //this.el.insertAdjacentHTML("beforeend","<a>123456</a>")
            document.body.appendChild(this.el)
            this.position = {
                left: window.innerWidth - this.el.clientWidth,
                top: (window.innerHeight - Math.random() * 100 - this.el.clientHeight)
            };
            this.speed = 80 + Math.random() * 3
            this.un_speed = 0;
            this.lastTime = +new Date();

            this.bindEvent();
            this.setPos();
        }
    }
    bindEvent() {
        this.el.addEventListener("mouseenter", () => {
            this.state = 1; console.log("over")
            this.stateChangeTime = +new Date();
        }, false)
        this.el.addEventListener("mouseleave", (ev) => {
            this.state = 2;
            this.stateChangeTime = +new Date();
        }, false)
    }
    tick(currTime: number) {
        console.log("tick")
        var duration = (currTime - this.lastTime) / 1000;
        //加速或减速
        if (this.state == 1) {
            this.un_speed = this.easeIn(0, this.speed, (currTime - this.stateChangeTime) / 1000, .3)
            if (this.un_speed >= this.speed) {
                this.un_speed = this.speed;
                this.state = 0;
            }
        }
        else if (this.state == 2) {
            this.un_speed = this.speed - this.easeIn(0, this.speed, (currTime - this.stateChangeTime) / 1000, .3);
            if (this.un_speed <= 0) {
                this.un_speed = 0;
                this.state = 0;
            }
        }
        //判断当前位置
        var distance = duration * (this.speed - this.un_speed);
        this.position.left -= distance;
        this.setPos();
        this.lastTime = +new Date();
        //已经脱离屏幕
        if (this.position.left < 0 - this.el.clientWidth) {
            document.body.removeChild(this.el);
            return false;
        }
        return true
    }

    setPos() {
        this.el.style.left = this.position.left + "px"
        this.el.style.top = this.position.top + "px"
        //this.el.style.transform=`translate(${this.position.left}px)`
    }

    easeIn(start: number, alter: number, curTime: number, dur: number) {
        return start + Math.pow(curTime / dur, 2) * alter;
    }
}
